package com.jeeplus.modules.monitor.utils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jeeplus.common.config.Global;
import com.jeeplus.common.utils.FileUtils;

/**
 * mysql数据库备份工具类
 * @author mall
 *
 */
public class MySQLBackupUtil {
	private static Logger logger= LoggerFactory.getLogger(MySQLBackupUtil.class);
	
	public static boolean startBackUp(String fileName) {
		try {
			String url = Global.getConfig("jdbc.url");
			String[] str = url.split("\\?")[0].replace("jdbc:mysql://", "").split("\\/");

			String host = str[0].split(":")[0];
			String dataBase = str[1];
			String username = Global.getConfig("jdbc.username");
			String password = Global.getConfig("jdbc.password");
			
			Calendar cal = Calendar.getInstance();
	        int year = cal.get(Calendar.YEAR);
	        int month = cal.get(Calendar.MONTH ) + 1;
	        
			String path = new File(Global.getUserfilesBaseDir()) + Global.USERFILES_BASE_URL + "backup/" + year + "/" + month + "/";
			return exportDatabaseTool(host, username, password, path, fileName, dataBase);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public static boolean startBackUp() throws IOException {
		return startBackUp(new SimpleDateFormat("yyyyMMdd").format(new Date()) + ".sql");
	}

	public static boolean exportDatabaseTool(String hostIP, String userName, String password, String savePath, String fileName, String databaseName) {
		try {
			File saveFile = new File(savePath);
			if (!saveFile.exists()) {// 如果目录不存在
				saveFile.mkdirs();// 创建文件夹
			}
			if (!savePath.endsWith(File.separator)) {
				savePath = savePath + File.separator;
			}
			
			File newFile = FileUtils.getAvailableFile(savePath + fileName, 0);
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.append("mysqldump").append(" --opt").append(" -h").append(hostIP);
			stringBuilder.append(" --user=").append(userName).append(" --password=").append(password).append(" --lock-all-tables=true");
			stringBuilder.append(" --result-file=").append(newFile.getPath()).append(" --default-character-set=utf8 ").append(databaseName);

			Process process = Runtime.getRuntime().exec(stringBuilder.toString());
			if (process.waitFor() == 0) {// 0 表示线程正常终止。
				return true;
			}
		} catch (Exception e) {
			logger.error("数据库备份失败：" + e.getMessage());
			e.printStackTrace();
		}
		return false;
	}
}
